<template>
    <div class="weekly-form">
      <h2>{{ formData.reportID ? "编辑周报" : "新增周报" }}</h2>
      <form @submit.prevent="saveWeekly">
        <div>
          <label for="reportTitle">周报标题:</label>
          <input id="reportTitle" v-model="formData.reportTitle" type="text" required />
        </div>
        <div>
          <label for="username">作者用户名:</label>
          <input id="username" v-model="formData.username" type="text" required />
        </div>
        <div>
          <label for="reportContent">周报内容:</label>
          <textarea id="reportContent" v-model="formData.reportContent" required></textarea>
        </div>
        <div>
          <label for="submitTime">提交时间:</label>
          <input id="submitTime" v-model="formData.submitTime" type="text" placeholder="yyyy-mm-ddThh:mm:ss" />
        </div>
        <button type="submit">保存</button>
        <button type="button" @click="$emit('close')">取消</button>
      </form>
    </div>
  </template>
  
  <script>
  import axios from "axios";
  
  export default {
    name: "WeeklyForm",
    props: {
      weekly: Object,
    },
    data() {
      return {
        formData: {
          reportID: null,
          username: "",
          reportTitle: "",
          reportContent: "",
          submitTime: this.getCurrentTime(), // 默认设置为当前时间
        },
      };
    },
    watch: {
      weekly: {
        immediate: true,
        handler(newVal) {
          if (newVal) {
            this.formData = { ...newVal }; // 克隆对象，避免直接修改父组件数据
          } else {
            this.resetForm();
          }
        },
      },
    },
    methods: {
      // 获取当前时间，格式为 yyyy-mm-ddThh:mm:ss
      getCurrentTime() {
        const now = new Date();
        return now.toISOString(); // 返回 ISO 格式的日期时间
      },
      saveWeekly() {
        const api = this.formData.reportID ? "/weekly/update" : "/weekly/add";
        const method = this.formData.reportID ? "put" : "post";
  
        // 发送请求到后端
        axios[method](api, this.formData)
          .then(() => {
            alert("保存成功！");
            this.$emit("save"); 
            this.$emit("close"); 
          })
          .catch((error) => {
            console.error("保存周报失败:", error);
            alert("保存失败，请检查输入！");
          });
      },
      resetForm() {
        // 重置表单数据为新增状态
        this.formData = {
          reportID: null,
          username: "",
          reportTitle: "",
          reportContent: "",
          submitTime: this.getCurrentTime(), // 重置提交时间为当前时间
        };
      },
    },
  };
  </script>
  
  <style scoped>
  .weekly-form {
    background-color: #f9f9f9;
    padding: 20px;
    border-radius: 8px;
    width: 300px;
  }
  
  form div {
    margin-bottom: 10px;
  }
  
  label {
    display: block;
    margin-bottom: 5px;
  }
  
  input,
  textarea {
    width: 100%;
    padding: 8px;
  }
  
  textarea {
    height: 100px;
  }
  </style>
  